<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form'
import type { VxeTableGridOptions } from '#/adapter/vxe-table'

import { computed, h, ref } from 'vue'
import { Page } from '@vben/common-ui'
import { Button, message, Input } from 'ant-design-vue'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { getOutSelectIndex, exportOutSelectData } from '#/api/outSelect'
import { getMaterialTypeOptions } from '#/api/materialBatchBill'
import { getWarehouseList, getSupplyList } from '#/api/common'
import { useDebounceFn } from '@vueuse/core'
import dayjs from 'dayjs'
import { AntDownloadOutlined } from '@vben/icons'

interface RowType {
  [key: string]: any
}
const params = ref<any>({ quick_search: '' })
const selectedRows = ref<RowType[]>([])
const formData = ref<any>({})
// 关键字和加载状态
const keyword = ref({
  warehouse_id: '',
  factory_id: '',
  material_category_id: '',
})

// 获取仓库选项
const fetchWarehouseOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getWarehouseList({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'id',
    initValue: keyword ? '' : formData.value?.ware_house_id,
    select: true,
  })
  return list.map((item: any) => ({
    label: `${item.warehouse_code}/${item.warehouse_name}`,
    value: item.id,
  }))
}

// 获取供应商选项
const fetchFactoryOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getSupplyList({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'id',
    initValue: keyword ? '' : formData.value?.factory_id,
    select: true,
  })
  return list.map((item: any) => ({
    label: item.SupplyNa,
    value: item.id,
  }))
}

// 获取物料类型选项
const fetchMaterialTypeOptions = async ({ keyword = '' }: Record<string, any>) => {
  try {
    const { list } = await getMaterialTypeOptions({
      quick_search: keyword,
      page: 1,
      limit: 30,
      initKey: 'id',
      initValue: keyword ? '' : formData.value?.material_type,
      select: true,
    })
    return list.map((item: any) => ({
      label: item.name,
      value: item.id,
    }))
  } catch (error) {
    console.error('获取物料类型选项失败:', error)
    return []
  }
}

// 默认排序
const defaultSort: { field: string; order: '' | 'asc' | 'desc' | null } = {
  field: 'send_date',
  order: 'desc',
}

// 表单配置
const formOptions: VbenFormProps = {
  wrapperClass: 'grid-cols-5',
  schema: [
    {
      component: 'Select',
      fieldName: 'type',
      label: '单据类型',
      operator: '=',
      componentProps: {
        options: [
          { label: '全部', value: '' },
          { label: '采购退料', value: '采购退料' },
          { label: '生产发料', value: '生产发料' },
          { label: '调仓单', value: '调仓单' },
        ],
        placeholder: '请选择',
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'record_sn',
      label: '出货单号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'RangePicker',
      fieldName: 'send_date',
      label: '出货日期',
      operator: 'RANGE',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      component: 'Input',
      fieldName: 'goods_no',
      label: '货号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'product_sn',
      label: '生产制单号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'purchase_sn',
      label: '手工单号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'ApiSelect',
      fieldName: 'ware_house_id',
      label: '仓库',
      operator: '=',
      componentProps: () => ({
        api: fetchWarehouseOptions,
        filterOption: false,
        onSearch: useDebounceFn((value: string) => {
          keyword.value.warehouse_id = value
        }, 300),
        params: { keyword: keyword.value.warehouse_id || undefined },
        allowClear: true,
        showSearch: true,
        immediate: false,
        alwaysLoad: true,
        visibleEvent: 'onFocus',
        onDropdownVisibleChange: (open: boolean) => {
          console.log('visible', open)
          if (open) keyword.value.warehouse_id = ''
        },
      }),
    },
    {
      component: 'ApiSelect',
      fieldName: 'factory_id',
      label: '供应商',
      operator: '=',
      componentProps: () => ({
        api: fetchFactoryOptions,
        filterOption: false,
        onSearch: useDebounceFn((value: string) => {
          keyword.value.factory_id = value
        }, 300),
        params: { keyword: keyword.value.factory_id || undefined },
        allowClear: true,
        showSearch: true,
        immediate: false,
        alwaysLoad: true,
        visibleEvent: 'onFocus',
        onDropdownVisibleChange: (open: boolean) => {
          console.log('visible', open)
          if (open) keyword.value.factory_id = ''
        },
      }),
    },
    {
      component: 'ApiSelect',
      fieldName: 'material*material_type',
      label: '物料类型',
      operator: 'IN',
      componentProps: () => ({
        api: fetchMaterialTypeOptions,
        allowClear: true,
        showSearch: true,
        optionFilterProp: 'label',
        mode: 'multiple',
        immediate: false,
        visibleEvent: 'onFocus',
      }),
    },
    {
      component: 'Input',
      fieldName: 'material_sku*sku_sn',
      label: '物料编码',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'material_name',
      label: '物料名称',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'remark',
      label: '备注',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
  ],
  showCollapseButton: true,
  collapsed: true,
  submitOnChange: false,
  submitOnEnter: true,
}

// 表格配置
const gridOptions: VxeTableGridOptions<RowType> = {
  border: true,
   checkboxConfig: {
    highlight: true,
    reserve: true,
    showReserveStatus: true,
  },
  rowConfig: {
    useKey: true,
    keyField: 'id',
    // isCurrent: true,
    isHover: true,
  },
  columnConfig: { useKey: true },
  // cellConfig: { height: 60 },
  columns: [
    { type: 'checkbox', width: 50 },
    { field: 'type', width: 120, title: '单据类型', sortable: true, slots: { default: 'typeTag' } },
    { field: 'record_sn', width: 150, title: '出货单号', sortable: true },
    {
      field: 'send_date',
      width: 100,
      title: '出货日期',
      sortable: true,
      formatter: ({ cellValue }) => {
        if (cellValue) {
          return dayjs(cellValue).format('YYYY-MM-DD')
        }
        return '-'
      },
    },
    { field: 'warehouse_info', width: 150, title: '仓库', slots: { default: 'warehouseInfo' } },
    { field: 'factory_info', width: 150, title: '供应商', slots: { default: 'factoryInfo' } },
    { field: 'material_category_info', width: 100, title: '物料类型', slots: { default: 'materialCategoryInfo' } },
    { field: 'material_sku_info', width: 120, title: '物料编码', slots: { default: 'skuInfo' } },
    { field: 'material_info', width: 120, title: '物料名称', slots: { default: 'materialInfo' } },
    { field: 'material_color_info', width: 80, title: '颜色', slots: { default: 'colorInfo' } },
    { field: 'material_spec_info', width: 80, title: '规格', slots: { default: 'specInfo' } },
    { field: 'check_num', width: 120, title: '核料数量', sortable: true },
    { field: 'check_unit', width: 120, title: '核料单位' },
    { field: 'check_price', width: 120, title: '核料单价', sortable: true },
    { field: 'check_total_price', width: 120, title: '核料金额', sortable: true },
    { field: 'unit_rate', width: 120, title: '换算比例', sortable: true },
    { field: 'num', width: 120, title: '采购数量', sortable: true },
    { field: 'unit', width: 120, title: '采购单位' },
    { field: 'price', width: 120, title: '采购单价', sortable: true },
    { field: 'total_price', width: 120, title: '采购金额', sortable: true },
    { field: 'goods_no', width: 120, title: '货号', sortable: true },
    { field: 'product_sn', width: 120, title: '生产制单号', sortable: true },
    { field: 'purchase_sn', width: 120, title: '手工单号', sortable: true },
    { field: 'remark', width: 120, title: '备注', sortable: true },
  ],
  exportConfig: {
    filename: '出库明细',
    type: 'xlsx',
    remote: false,
  },
  height: 'auto',
  keepSource: true,
  pagerConfig: { pageSize: 20 },
  proxyConfig: {
    ajax: {
      query: async ({ page, sort }) => {
        const search = await gridApi.formApi.getFiltersValues()
        const { list, total } = await getOutSelectIndex({
          page: page.currentPage,
          limit: page.pageSize,
          search,
          quick_search: params.value.quick_search,
          order: sort.field && sort.order ? `${sort.field},${sort.order}` : `${defaultSort.field},${defaultSort.order}`,
        })
        return { items: list, total: total }
      },
    },
    sort: true,
  },
  sortConfig: { defaultSort, remote: true },
  toolbarConfig: { custom: true, export: true, refresh: true, resizable: true, search: true, zoom: true },
  id: 'out_select_list',
  customConfig: {
    storage: true,
  },
}

// 初始化表格
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {
    checkboxChange: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    },
    checkboxAll: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    }
  },
})
const debouncedReload = useDebounceFn(gridApi.reload, 1000)

// 导出功能 - 使用示例中的导出方法
const handleExport = async () => {
  const hide = message.loading('正在导出...', 0)
  try {
    const search = await gridApi.formApi.getFiltersValues()
    await exportOutSelectData({
      ...search,
      export: true,
    })
    message.success('导出成功')
  } catch (error) {
    message.error('导出失败')
    console.error('导出错误:', error)
  } finally {
    hide()
  }
}

// 获取超链接显示
const getWarehouseInfo = (row: any) => {
  const warehouse = row.warehouse
  if (warehouse) {
    return `${warehouse.warehouse_code}/${warehouse.warehouse_name}`
  }
  return '-'
}

const getFactoryInfo = (row: any) => {
  const factory = row.supply
  if (factory) {
    return factory.SupplyNa
  }
  return '-'
}

const getMaterialCategoryInfo = (row: any) => {
  const material = row.material
  if (material) {
    return material.material_type
  }
  return '-'
}

const getSkuInfo = (row: any) => {
  const sku = row.material_sku
  if (sku) {
    return sku.sku_sn
  }
  return '-'
}

const getMaterialInfo = (row: any) => {
  const material = row.material
  if (material) {
    return material.material_name
  }
  return '-'
}

const getColorInfo = (row: any) => {
  const color = row.material_color
  if (color) {
    return color.name
  }
  return '-'
}

const getSpecInfo = (row: any) => {
  const spec = row.material_spec
  if (spec) {
    return spec.guige
  }
  return '-'
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <Button class="mr-2" type="primary" @click="handleExport">
          <AntDownloadOutlined />
          导出
        </Button>
      </template>
      <template #toolbar-tools>
        <div>
          <Input type="text" placeholder="通过货号、生产单号搜索" v-model:value="params.quick_search" :allow-clear="true" @input="debouncedReload" />
        </div>
      </template>

      <template #typeTag="{ row }">
        <span v-if="row.type === '采购退料'" class="text-blue-600">{{ row.type }}</span>
        <span v-else-if="row.type === '生产发料'" class="text-green-600">{{ row.type }}</span>
        <span v-else-if="row.type === '调仓单'" class="text-orange-600">{{ row.type }}</span>
        <span v-else>{{ row.type || '-' }}</span>
      </template>

      <template #warehouseInfo="{ row }">
        <span>{{ getWarehouseInfo(row) }}</span>
      </template>

      <template #factoryInfo="{ row }">
        <span>{{ getFactoryInfo(row) }}</span>
      </template>

      <template #materialCategoryInfo="{ row }">
        <span>{{ getMaterialCategoryInfo(row) }}</span>
      </template>

      <template #skuInfo="{ row }">
        <span>{{ getSkuInfo(row) }}</span>
      </template>

      <template #materialInfo="{ row }">
        <span>{{ getMaterialInfo(row) }}</span>
      </template>

      <template #colorInfo="{ row }">
        <span>{{ getColorInfo(row) }}</span>
      </template>

      <template #specInfo="{ row }">
        <span>{{ getSpecInfo(row) }}</span>
      </template>
    </Grid>
  </Page>
</template>
